<?php

namespace app\api\service;

use app\lib\exception\TokenException;
use app\lib\exception\ForbiddenException;
use app\lib\enum\ScopeEnum;

class Token{

    /* 生成随机验证码 */
    public function generateToken()
    {
        $randChars = getRandChar(32);
        $timestamp = $_SERVER['REQUEST_TIME_FLOAT'];
        $salt = config('secure.salt');
        return md5($randChars.$timestamp.$salt);
    }

    /* 根据token获取缓存中的值 */
    public static function getCurrentTokenVal($key)
    {
        $token = request()->header('token');
        if(!$token){
            throw new TokenException([
                'msg' => 'token令牌有误'
            ]);
        }        
        $result = json_decode(cache($token),true);
        if(!is_array($result) || !array_key_exists($key,$result)){
            throw new TokenException([
                'msg' => '缓存中不存在该值'
            ]);
        }
        return $result[$key];
    }

    /* 获取当前用户ID */
    public static function getCurrentUID()
    {
        $uid = self::getCurrentTokenVal('uid');
        return $uid;
    }

    /* 前置校验权限 普通用户 */
    public static function needPrimayScope()
    {
        $scope = self::getCurrentTokenVal('scope');
        if($scope != ScopeEnum::User){
            throw new ForbiddenException();
        }
        return true;
    }

    /* 前置校验权限 全部用户 */
    public static function needExclusiveScope()
    {
        $scope = self::getCurrentTokenVal('scope');
        if($scope >= ScopeEnum::User){
            throw new ForbiddenException();
        }
        return true;
    }

    /* 检测下单用户是否一致 */
    public static function checkUserOrder($user_id)
    {
        $uid = self::getCurrentUID();
        if($uid != $user_id){
            return false;
        }
        return true;
    }

}